package com.zoro.dyformservice.business.user.service;

import com.zoro.dyformservice.business.user.entity.UserInfoEntity;
import com.zoro.dyformservice.business.user.entity.UserInfoExtEntity;
import com.zoro.dyformservice.business.user.repository.UserRepository;
import com.zoro.dyformservice.constants.response.common.YesOrNo;
import com.zoro.dyformservice.utils.EncryptUtils;
import com.zoro.dyformservice.utils.KeyGenerator;
import com.zoro.dyformservice.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserInfoModifyService {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private final UserRepository userRepository;

    public UserInfoModifyService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public UserInfoEntity save(UserInfoEntity userInfo) {
        UserInfoEntity user;
        if (StringUtils.isBlank(userInfo.getUserId())) {
            user = this.handleInsert(userInfo);
        } else {
            user = this.handleUpdate(userInfo);
        }
        userRepository.save(user);
        return userInfo;
    }

    private UserInfoEntity handleInsert(UserInfoEntity userInfo) {
        userInfo.setUserId(KeyGenerator.generateUuid());
        String password = EncryptUtils.sha256(userInfo.getPassword());
        userInfo.setDeleted(YesOrNo.NO);
        userInfo.setLocked(YesOrNo.NO);
        userInfo.setPassword(password);
        userInfo.setCreateTime(new Date());

        UserInfoExtEntity extEntity = userInfo.getUserInfoExt();
        if (extEntity == null) {
            return userInfo;
        }
        extEntity.setId(KeyGenerator.generateUuid());
        // 这个不能少
        extEntity.setUserInfo(userInfo);
        return userInfo;
    }

    private UserInfoEntity handleUpdate(UserInfoEntity userInfo) {
        return userInfo;
    }

    public void test() {

        String id = "1";
        YesOrNo target = YesOrNo.NO;
        UserInfoEntity infoEntity1 = this.userRepository.findByUserId(id);
        logger.info("info1 >>>> id: {}, deleted: {}, name: {}", infoEntity1.getUserId(), infoEntity1.getDeleted(),
                infoEntity1.getUserName());

        logger.info("update info{userid={}} delete to {}.", infoEntity1.getUserId(), target);
        int record = this.userRepository.updateDeleted(id, target);
        logger.info("update finished: {}", record);
        UserInfoEntity infoEntity2 = this.userRepository.findByUserId(id);
        logger.info("info2 >>>> id: {}, deleted: {}", infoEntity2.getUserId(), infoEntity2.getDeleted());
    }
}
